<!-- 今日待提货-交货签收页signPage/index -->
<template>
  <view class="body">
    <!-- 承运单号 -->
    <view class="bill_card flex_between">
      <view>承运单号：{{ orderList?.billNo || '暂无数据' }}</view>
      <view class="blue_font" @click="toBillDetailsPage">运单详情></view>
    </view>
    <view class="card">
      <!-- 地址簿 -->
      <view class="address_card">
        <view class="flex_start">
          <image class="icon" src="@/assets/images/pages2/signPage/send.png" />
          <view>
            <view class="person flex_start">
              <span>{{ orderList?.shipper || '暂无数据' }}</span>
              <span>{{ orderList?.shipperMobile ? orderList?.shipperMobile : orderList?.shipperTel }}</span>
            </view>
            <view class="info">{{ orderList?.shipperAdd || '暂无数据' }}</view>
          </view>
        </view>
        <view class="flex_start">
          <image class="icon" src="@/assets/images/pages2/signPage/save.png" />
          <view>
            <view class="person flex_start">
              <span>{{ orderList?.receiver || '暂无数据' }}</span>
              <span>{{ orderList?.receiverMobile ? orderList?.receiverMobile : orderList?.receiverTel }}</span>
            </view>
            <view class="info">{{ orderList?.receiverAdd || '暂无数据' }}</view>
          </view>
        </view>
      </view>
      <!-- 地址库位 -->
      <view class="house_card gray_bg">
        <view class="addr flex_between"
          ><span class="gray_font">开单处</span><span>{{ orderList?.startBranchName || '暂无数据' }}</span>
        </view>
        <view class="addr flex_between"
          ><span class="gray_font">库位</span><span>{{ orderList?.locationName || '暂无数据' }}</span></view
        >
        <view class="addr flex_between"
          ><span class="gray_font">仓储时长</span><span class="blue_font">{{ storageDuration || '暂无数据' }}</span></view
        >
      </view>
      <!-- 库位 -->
      <view></view>
    </view>

    <view class="card">
      <view class="tit">交货数量<span class="i">*</span></view>
      <view class="goods_card gray_bg">
        <view class="list_item flex_between" v-for="(item, index) in orderList?.goodsInfo" :key="index">
          <view class="flex_start">
            <span>{{ item.goodsName || '暂无数据' }}</span>
            <span :style="{ color: item.upNumber !== item.goodsNumber ? '#0966FF' : '#666' }">{{ filterGoodsNum(item) }}</span>
          </view>
          <nut-input-number v-model="inputValues[index]" min="0" :max="item.goodsNumber - item.upNumber" :value="item.goodsNumber - item.upNumber" />
        </view>
      </view>
    </view>

    <view class="card" v-if="saveMoneyShow">
      <view class="tit">保管费用<span class="i">*</span></view>
      <view class="save_card flex_start"><input class="input" v-model="saveMoney" min="5" :disabled="!saveMoneyShow" @input="handleSaveMoney" /><span>元</span> </view>
    </view>

    <view class="card">
      <view class="tit">签收人信息<span class="i">*</span></view>
      <view class="peop_card gray_bg">
        <view class="peop"><span class="left">姓名</span><input class="right input" v-model="formData.receiverName" placeholder="姓名" /></view>
        <view class="peop"><span class="left">联系方式</span><input class="right input" v-model="formData.receiverPhone" placeholder="联系方式" /></view>
        <view class="peop"><span class="left">身份证号码</span><input class="right input" v-model="formData.receiverIdNo" placeholder="请输入身份证号码" /> </view>
      </view>
    </view>

    <view class="card">
      <view class="tit">电子签名<span class="i">*</span></view>
      <view class="write_card gray_bg" v-if="signUrl">
        <img class="hand_img" :src="signUrl" />
      </view>
      <nut-button type="info" @click="toHandwritingBoard" v-if="signUrl" style="width: 100%; margin-top: 10rpx">重新绘制</nut-button>
      <view class="write_card gray_bg" v-else style="text-align: center" @click="toHandwritingBoard"> 点击绘制签名 </view>
    </view>

    <view class="card remark_card">
      <view class="tit">备注</view>
      <nut-textarea v-model="formData.remarks" limit-show max-length="500" placeholder="请输入备注信息" />
      <nut-uploader ref="uploadRef" :before-xhr-upload="beforeXhrUpload" v-model:file-list="fileList" :auto-upload="true" :is-preview="true" maximum="8"></nut-uploader>
      <!-- <nut-button type="success" @click="uploadImg">上传图片</nut-button> -->
    </view>
  </view>

  <view class="fixed_bottom" v-if="orderList.pickUpMode == '1' && !orderList.allPaid && orderList.clearingForm != 3">
    <view class="flex_start"
      ><span>合计</span> <span class="pay">￥{{ Number(saveMoney) + Number(allPay) }}</span
      ><a @click="showCost = true"
        ><span style="color: #0966ff">明细^</span>
        <RectDown /> </a
    ></view>
    <nut-button type="info" @click="toPay">确定交货(支付收银台)</nut-button>
  </view>

  <view class="fixed_bottom" v-else>
    <nut-button type="info" class="btn_confirm" @click="toSign">确定交货</nut-button>
  </view>

  <CostInfoModal :saveMoney="saveMoney" :showCost="showCost" @closeCostModal="closeCostModal" />
</template>

<script lang="ts" setup>
import Taro, { useDidShow, useReady, useRouter } from '@tarojs/taro'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import { reactive, ref, watch } from 'vue'
import useOrderStore from '@/store/order'
import useUserStore from '@/store/user'
import picker from '@/store/pick'

import { shBaseUrl } from '@/@api/urls'
import { checkPickup, getstorageDuration, pickGoods } from '@/@api/sign' // sign的接口
import CostInfoModal from '@/pages2/signPage/costInfoModal' // 价格合计

const router = useRouter()

/* 初始化数据变量 start */
useReady(() => {
  Taro.setNavigationBarTitle({
    title: '交货签收'
  })
  Taro.setNavigationBarColor({
    frontColor: '#000000',
    backgroundColor: '#ffffff'
  })
  getLocationTime() // 获取仓储时长
  getAllMoney() // 计算费用
})

const userStore = useUserStore()
const orderStore = useOrderStore()
const pickStore = picker()

const orderList = ref<any>()
orderList.value = orderStore.orderInfo

const inputValues = ref(pickStore.pickerInfo.inputValues) // 货物数量

// 表单的数据
const formData = ref({
  receiverIdNo: pickStore.pickerInfo.receiverIdNo, // 身份证
  receiverName: pickStore.pickerInfo.receiverName || orderList.value.receiver, // 签收人姓名
  receiverPhone: pickStore.pickerInfo.receiverPhone || orderList.value.receiverMobile, // 签收人手机号
  remarks: '' // 备注非必填
})

const storageDuration = ref() //仓储时长

// 获取仓储时长
async function getLocationTime() {
  const res = await getstorageDuration({ billNo: orderList.value.billNo }) //202302289
  if (res.data.code == 200) {
    // console.log(res.data.data, '仓储时长')
    // 计算天数
    const days = Math.floor(res.data.data / (24 * 60 * 60))
    // 计算剩余的秒数
    const remainingSeconds = res.data.data % (24 * 60 * 60)
    // 计算小时数
    const hours = Math.floor(remainingSeconds / (60 * 60))
    // 计算剩余的秒数
    const remainingSeconds2 = remainingSeconds % (60 * 60)
    // 计算分钟数
    const minutes = Math.floor(remainingSeconds2 / 60)
    storageDuration.value = `${days}天 ${hours}小时 ${minutes}分钟`
  }
}

// 跳转签名板回显签名图
const SignPic = ref('') // 签名字段
const signUrl = ref('') // 签名回显字段
useDidShow(() => {
  if (router.params.signUrl) {
    signUrl.value = router.params.signUrl
    sendSignPic(router.params.signUrl)
  }
})
function toHandwritingBoard() {
  pickStore.pickerInfo = {
    receiverName: formData.value.receiverName, // 姓名
    receiverPhone: formData.value.receiverPhone, // 手机号
    receiverIdNo: formData.value.receiverIdNo, // 身份证
    remarks: formData.value.remarks, // 备注
    inputValues: inputValues.value // 货物数量
  }
  Taro.navigateTo({
    url: '/pages2/signPage/handWrite'
  })
}

/* 合计费用明细 start */

const showCost = ref(false) // 明细显示
const allPay = ref(0)
const saveMoneyShow = ref(false) // 保管费是否显示
const saveMoney = ref(0) // 前端填写的保管费
function getAllMoney() {
  console.log(JSON.parse(JSON.stringify(orderList.value)), 'orderList计算待付款本地取出的')
  orderList.value.costList.forEach((item) => {
    allPay.value = allPay.value + (item.actualMoney - item.paidMoney)
  })
  console.log(allPay.value)
}

// 判断有无保管费
const params = {
  billNo: [orderList.value.billNo]
}

async function getcheckPickup() {
  const res = await checkPickup(params.billNo)
  if (res.data.code == 200) {
    console.log(res.data, '结果')
    if (res.data.data[0].hasStorageFee) {
      saveMoneyShow.value = true // 保管费是否存在
      saveMoney.value = res.data.data[0].manageFee
    } else {
      console.log('不显示')
    }
  }
}

// 监听保管费
function handleSaveMoney(event) {
  saveMoney.value = Number(event.detail.value)
}

// 监听费用判断是否调保管费接口
watch(
  allPay,
  (value) => {
    // console.log(value, 'allPay')
    if (value) {
      getcheckPickup()
    }
  },
  { immediate: true }
)

// 关闭费用窗口
function closeCostModal() {
  showCost.value = false
}
/* 合计费用明细 end */

/* 过滤货物信息-名称件数 */
function filterGoodsNum(val) {
  const { upNumber, goodsNumber } = val
  let goodsNum
  if (goodsNumber) {
    if (upNumber !== goodsNumber) {
      // goodsNum = upNumber !== 0 ? '(' + (goodsNumber - upNumber) + '/' + goodsNumber + ')' : '(' + goodsNumber + '/' + goodsNumber + ')'
      // goodsNum = upNumber !== 0 ? '(' + upNumber + '/' + goodsNumber + ')' : '(' + goodsNumber + '/' + goodsNumber + ')'

      goodsNum = upNumber !== 0 ? upNumber + '(已取)/' + goodsNumber + '(总数)' : '0(已取)/' + goodsNumber + '(总数)'
    } else {
      goodsNum = goodsNumber
    }
  }
  return `${goodsNum}件`
}

// 上传图片
const FilePic = ref('') // 图片字段
const uploadUrl = 'http://192.168.10.32:38080/selfmachine-system/workerOrder/filesUpload'
const uploadRef = ref()
const fileList = reactive<any>([])

const beforeXhrUpload = (taroUploadFile: any, options: any) => {
  const uploadTask = taroUploadFile({
    url: uploadUrl,
    filePath: options.taroFilePath,
    fileType: options.fileType,
    header: {
      'Content-Type': 'multipart/form-data',
      Authorization: userStore.token
      // Authorization: Taro.getStorageSync('token')
    },
    formData: {
      // billNo: orderStore.orderInfo.billNo
      billNo: orderList.value.billNo
    },
    name: options.name,
    success(response: { errMsg: any; statusCode: number; data: string }) {
      console.log(response.errMsg, response.statusCode, 'errMsg,statusCode')
      const res = JSON.parse(response.data)
      if (res.code == 200) {
        console.log(res.data.filePicUrl[0], '上传图片回调')
        FilePic.value += res.data.filePicUrl[0] + ';'
        fileList[fileList.length - 1].status = 'success'
        fileList[fileList.length - 1].message = '上传成功'
      } else {
        console.log('上传图片失败')
        Taro.showToast({
          title: '上传图片失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    fail(e: any) {
      console.log('上传图片失败')
      options.onFailure?.(e, options)
    }
  })
  options.onStart?.(options)
  uploadTask.progress((res: { progress: any; totalBytesSent: any; totalBytesExpectedToSend: any }) => {
    options.onProgress?.(res, options)
  })
}

function uploadImg() {
  uploadRef.value.submit()
}

// 上传签名
function sendSignPic(url) {
  Taro.uploadFile({
    // url: "http://192.168.10.32:38080/selfmachine-system/workerOrder/signPicUpload" + "?billNo=" + orderStore.orderInfo.billNo,
    url: shBaseUrl + '/selfmachine-system/workerOrder/signPicUpload' + '?billNo=' + orderList.value.billNo,
    filePath: url, // 签名的图
    header: {
      'Content-Type': 'multipart/form-data',
      Authorization: userStore.token
    },
    name: 'file',
    success(response) {
      const res = JSON.parse(response.data)
      if (res.code == 200) {
        console.log(res.data.signPicUrl, '上传签名回调')
        SignPic.value = res.data.signPicUrl // 拼接签名字段
      } else {
        Taro.showToast({
          title: '签名上传失败请重新签名',
          icon: 'none',
          duration: 1000
        })
      }
    }
  })
}

// 获取表单信息 签名图片 上传图片
function getFormVerify() {
  const pickNum = inputValues.value.length // 取货数量
  if (!pickNum) {
    Taro.showToast({
      title: '请选择交货数量',
      icon: 'none',
      duration: 1000
    })
    return
  }

  if (saveMoneyShow.value) {
    if (!saveMoney.value) {
      Taro.showToast({
        title: '请填写保管费',
        icon: 'none',
        duration: 1000
      })
      return
    } else if (saveMoney.value && saveMoney.value < 5) {
      Taro.showToast({
        title: '保管费不得低于5元',
        icon: 'none',
        duration: 1000
      })
      return
    }
  }

  if (!formData.value.receiverName) {
    Taro.showToast({
      title: '请填写姓名',
      icon: 'none',
      duration: 1000
    })
    return
  }

  if (!formData.value.receiverPhone) {
    Taro.showToast({
      title: '请填写联系方式',
      icon: 'none',
      duration: 1000
    })
    return
  } else {
    const phoneRegex = /^1[3456789]\d{9}$/
    if (!phoneRegex.test(formData.value.receiverPhone)) {
      Taro.showToast({
        title: '手机号格式错误',
        icon: 'none',
        duration: 1000
      })
      return
    }
  }

  if (!formData.value.receiverIdNo) {
    Taro.showToast({
      title: '请填写身份证号',
      icon: 'none',
      duration: 1000
    })
    return
  } else {
    const idNumberRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (!idNumberRegex.test(formData.value.receiverIdNo)) {
      Taro.showToast({
        title: '身份证格式错误',
        icon: 'none',
        duration: 1000
      })
      return
    }
  }

  if (!SignPic.value) {
    Taro.showToast({
      title: '请签名',
      icon: 'none',
      duration: 1000
    })
    return
  }

  // 如果有图片判断图片是否都成功了
  if (fileList) {
    console.log(fileList, '图片数据校验')

    const allTrue = fileList.every((obj) => obj.status == 'success')
    if (allTrue) {
      console.log('全都上传成功')
    } else {
      console.log('没全部上传成功')
      Taro.showToast({
        title: '请移除或替换上传失败的图片',
        icon: 'none',
        duration: 1000
      })
      return
    }
  }

  return true
}

// 重组我要交货入参
function setFormData() {
  const infoArray = inputValues.value
    .map((quantity, index) => {
      if (!quantity) return // 如果quantity为空值，则直接返回

      return {
        num: quantity,
        receiverIdNo: formData.value.receiverIdNo,
        receiverName: formData.value.receiverName,
        receiverPhone: formData.value.receiverPhone,
        companyNo: orderList.value.startBranch,
        customerIdNo: '',
        orderId: orderList.value.billNo,
        goodsName: orderList.value.goodsInfo[index].goodsName,
        ssogId: orderList.value.goodsInfo[index].ssogId,
        ispicked: orderList.value.goodsInfo[index].goodsNumber == orderList.value.goodsInfo[index].upNumber,
        remarks: formData.value.remarks,
        filePic: FilePic.value.slice(0, -1),
        signPic: SignPic.value
      }
    })
    .filter(Boolean) // 过滤掉空值
  return infoArray
}

// 跳转收银台带保管费
function toPay() {
  const flag = getFormVerify()
  if (!flag) {
    console.log('没通过校验')
    return
  }
  // 格式化数据
  console.log(setFormData(), '存入的infoArray', formData.value, '表单数据', saveMoney, 'saveMoney去跳收银台')
  pickStore.pickerData = setFormData()
  Taro.navigateTo({
    url: `/pages2/pay/index?saveMoney=${saveMoney.value}&fromPage=sign`
  })
}

// 点击我要交货按钮 调签名-成功调交货接口&上传图片
function toSign() {
  const flag = getFormVerify()
  if (!flag) {
    console.log('没通过校验')
    return
  } else {
    pickGood()
  }
}

// 交货接口
async function pickGood() {
  const pickParams = setFormData()
  console.log(pickParams, '交货接口入参')
  // return
  const { data } = await pickGoods(pickParams)
  if (data.code == 200) {
    console.log(data, '交货成功跳转交货成功详情页')
    // 跳转交货签收详情页
    Taro.navigateTo({
      url: `/pages2/pay/info?billFlag=sign`
    })
  }
}

// 跳转至运单详情页
function toBillDetailsPage() {
  Taro.navigateTo({
    url: '/pages2/waybillPage/signInfo'
  })
}
</script>

<style lang="scss">
.body {
  width: 750rpx;
  margin: 0 auto;
  background: #f5f5f5;
  padding: 16rpx 0;
  padding-bottom: 150rpx;
}

.flex_start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.flex_between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex_center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.blue_font {
  color: #0966ff;
}

.gray_font {
  color: #666;
}

.bill_card {
  width: 702rpx;
  height: 72rpx;
  padding: 20rpx 24rpx;
  margin: 0 auto;
  box-sizing: border-box;
  background: url('../../assets/images/pages2/signPage/top.png') 702rpx 72rpx;
  background-size: 100% 100%;
  font-size: 24rpx;
}

.card {
  width: 702rpx;
  margin: 0 auto;
  padding: 24rpx;
  box-sizing: border-box;
  background: #fff;
  margin: 16rpx auto;
  font-size: 24rpx;

  .tit {
    font-size: 32rpx;
    color: #252525;
    font-weight: bold;
    margin-bottom: 24rpx;

    .i {
      display: inline;
      color: #fa5151;
    }
  }

  .gray_bg {
    width: 654rpx;
    box-sizing: border-box;
    background: #f5f5f5;
  }

  .addr {
    margin-bottom: 16rpx;
  }

  .addr:last-child {
    margin-bottom: 0;
  }
}

.address_card {
  font-size: 32rpx;

  .icon {
    width: 75rpx;
    height: 75rpx;
    position: relative;
    top: 10rpx;
  }

  .person {
    font-weight: 700;
    color: #252525;

    span:first-child {
      margin-right: 24rpx;
    }
  }

  .info {
    font-weight: 400;
    font-size: 24rpx;
    color: #666666;
  }
}

.house_card {
  padding: 24rpx;
  font-size: 24rpx;
}

.goods_card {
  padding: 24rpx;
  font-size: 26rpx;

  .list_item {
    width: 90%;
    padding-bottom: 10rpx;
    border-bottom: 1rpx solid #f5f5f5;
    border-radius: 8rpx;
  }
}

.save_card {
  font-size: 28rpx;

  .input {
    width: 602rpx;
    height: 88rpx;
    border-radius: 8rpx;
    background: #f5f5f5;
    margin-right: 24rpx;
    padding-left: 20rpx;
  }

  .input::placeholder {
    color: #999 !important;
    padding-left: 20rpx !important;
  }
}

.peop_card {
  padding: 0 24rpx;
  font-size: 28rpx;

  .peop {
    display: flex;
    text-align: left;
    height: 88rpx;
    line-height: 88rpx;
    border-bottom: 1rpx solid #e7e7e7;

    .left {
      flex: 1;
    }

    .right {
      flex: 2;
    }

    .input {
      height: 88px;
    }
  }

  .peop:last-child {
    border-bottom: none;
  }
}

.write_card {
  background: #f8f9fa;
  border: 1rpx solid #c4c4c4;
  border-radius: 8rpx;
  height: 330rpx;
  width: 100%;
  box-sizing: border-box;
  color: #0966ff;
  font-size: 22rpx;
  font-weight: 400;
  display: flex;
  justify-content: center;
  align-items: center;

  .hand_img {
    height: 300rpx;
    width: 100%;
  }
}

.rewrite {
  width: 100%;
  height: 20rpx;
  line-height: 20rpx;
  color: #fff;
  background: #0966ff;
  margin-top: 10rpx;
  text-align: center;
  padding: 10rpx 0;
}

.remark_card {
  .nut-textarea {
    padding: 0;
    margin-bottom: 30rpx;

    .nut-textarea__textarea {
      width: 654rpx;
      height: 216rpx;
      border-radius: 8rpx;
      margin: 0 auto;
      background: #f5f5f5;
      padding: 24rpx;
      box-sizing: border-box;
    }
  }
}

.fixed_bottom {
  width: 100vw;
  height: 128rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 128rpx;
  box-sizing: border-box;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  color: #666;
  font-size: 24rpx;
  padding: 20rpx 24rpx;
  z-index: 99999;

  .pay {
    font-size: 40rpx;
    color: #0966ff;
    margin: 0 26rpx;
  }

  .btn_confirm {
    width: 100%;
  }
}

/* 地址簿 */

.center {
  margin-top: 16rpx;
  width: 700rpx;
  box-sizing: border-box;
  padding: 27rpx;
  background-color: #fff;
  border-radius: 10rpx;

  .top {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-top: 40rpx;

    image {
      width: 60rpx;
      height: 60rpx;
      margin-top: -10rpx;
    }

    .centers {
      width: 572rpx;
      border-bottom: 1px solid #ccc;
      padding-bottom: 32rpx;
      display: flex;
      justify-content: space-between;

      .right {
        font-size: 23rpx;
        align-self: center;
        color: #bcbec5;
      }
    }

    .text {
      // height: 32rpx;
      font-size: 20rpx !important;
    }

    p {
      display: flex;
      font-size: 48rpx;
      color: #666666;

      span {
        margin-right: 20rpx;
        font-size: 28rpx;
        font-weight: 700;
        line-height: 40rpx;
        color: #252525;
      }

      font-size: 24rpx;
    }
  }

  .bottoms {
    display: flex;
    width: 572rpx;
    margin-top: 32rpx;
    font-size: 28rpx;

    span {
      margin-right: 24rpx;
    }
  }

}
  .nut-uploader__preview {
    margin-right: 18rpx;
  }
</style>
